import 'package:flutter/cupertino.dart';
import 'package:flutter_menu/app_config.dart';
import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/data/provider/category_provider.dart';
import 'package:flutter_menu/data/provider/electronic_provider.dart';
import 'package:flutter_menu/data/provider/product_provider.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/widgets/load_container.dart';
import 'package:get/get.dart';
import 'package:objectbox/objectbox.dart';

import '../../data/menu_repository.dart';
import '../../menu_page.dart';

class OrderController extends GetxController
    with GetSingleTickerProviderStateMixin {
  static OrderController get to => Get.find();

  CategoryProvider categoryProvider = Get.find<CategoryProvider>();

  ElectronicProvider electronicProvider = Get.find<ElectronicProvider>();

  ProductProvider productProvider = Get.find<ProductProvider>();

  static const orderPageStatusPara = "orderPageStatusPara";
  static const productUuidPara = "productUuidPara";

  bool showSpecOptionDialog = false;

  // 菜单列表
  List<CustomMenuModel> customMenuList = [];

  //分类列表
  List<CustomMenuListCategoryList> categoryList = [];

  //菜品列表
  RxList<CategoryListProductList> productList = <CategoryListProductList>[].obs;

  //当前分类名称
  String? _currentCategoryName;

  String? get currentCategoryName => _currentCategoryName;

  set currentCategoryName(String? categoryName) {
    _currentCategoryName = categoryName;

    // 刷新菜品列表
    onLoadProductList();
  }

  // 菜品列表加载页面控制器
  LoadController? loadThumbnailController = LoadController();

  final Rx<CategoryListProductList?> _currentProduct =
      Rx<CategoryListProductList?>(null);

  void setCurrentProduct(CategoryListProductList? item) {
    _currentProduct.value = item;
  }

  // 是否显示订单详情（大图）
  bool get isShowDetail {
    return _currentProduct.value != null;
  }

  // 跳转到大图详情页
  void showOrderDetail(CategoryListProductList item) {
    setCurrentProduct(item);
    setTabDefault();
  }

  void dismissDetailShow() {
    setCurrentProduct(null);
  }

  CategoryListProductList? getProductWithFilterSpec() {
    var product = _currentProduct.value;

    // 过滤掉规格为停售的规格
    product?.dishList = ToMany(
        items: product.dishList.where((dish) {
      return !productProvider.isSpecStopped(
          product.productUuid ?? "", dish.productSpecsUuid ?? "");
    }).toList());
    return product;
  }

  // Page View 页（相对于底部tab缺少了分类， 因为分类是overlay，单独图层）
  var currentPageIndex = OrderTabType.tabThumbnail.obs;

  bool isInSearchPage() {
    return currentPageIndex.value == OrderTabType.tabSearch;
  }

  // tab 菜单
  var currentTabIndex = OrderTabType.tabThumbnail.obs;

  // 切换tab 菜单
  void setTabIndex(OrderTabType type) {
    if (type != currentTabIndex.value) {
      debugPrint("set tab index: $type");
      currentTabIndex.value = type;
      if (type != OrderTabType.tabCategory) {
        currentPageIndex.value = type;
      }
    }
  }

  void setTabDefault() {
    setTabIndex(OrderTabType.tabThumbnail);
  }

  void resetCategoryTab() {
    setTabIndex(currentPageIndex.value);
  }

  @override
  void onInit() {
    super.onInit();

    initData();
  }

  void checkRouteParams() {
    var pageStatus =
        OrderPageStatus.fromString(Get.parameters[orderPageStatusPara]);
    var productUuid = Get.parameters[productUuidPara];
    debugPrint("init orderController: $pageStatus");
    switch (pageStatus) {
      case null:
      // do nothing
      case OrderPageStatus.thumbnailPage:
      // do nothing
      case OrderPageStatus.detailPage:
        var productItem = productList.firstWhereOrNull((product) {
          return product.productUuid == productUuid;
        });
        if (productItem != null) {
          showOrderDetail(productItem);
        }
      case OrderPageStatus.specOptionPage:
        var productItem = productList.firstWhereOrNull((product) {
          return product.productUuid == productUuid;
        });
        if (productItem != null) {
          showSpecOptionDialog = true;
          showOrderDetail(productItem);
        }
    }
  }

  Future<void> initData() async {
    categoryList = await getCategoriesWithProductStatus();
    await onLoadProductList();

    checkRouteParams();
  }

  // 获取所有分类，并附加是否有产品的状态
  Future<List<CustomMenuListCategoryList>>
      getCategoriesWithProductStatus() async {
    var filterMenusWithImages =
        await electronicProvider.filterMenusWithImages();

    var menuId = ShopCarController.to.menuId;
    customMenuList = categoryProvider.getCustomMenuList(
        electronicConfigList: filterMenusWithImages, filterTable: menuId);

    final categories =
        categoryProvider.getCategoryList(customMenuList: customMenuList);

    // 遍历分类，检查每个分类是否有产品
    return categories;
  }

  List<CustomMenuModel> getMenuListForProduct() {
    return categoryProvider.getCategoryListWithProductId(
        _currentProduct.value?.productUuid,
        customMenuList: customMenuList);
  }

  @override
  void onClose() {
    super.onClose();
    loadThumbnailController?.dispose();
    loadThumbnailController = null;
  }

  Future<void> onLoadProductList() async {
    loadThumbnailController?.loading();
    var elecMenuList = await electronicProvider.getElecMenuList();
    var prepareProductList = categoryProvider.prepareProductList(
        allCustomMenus: customMenuList,
        electronicMenus: elecMenuList,
        filterCategoryName: currentCategoryName);
    if (prepareProductList.isEmpty) {
      // 空数据
      loadThumbnailController?.empty();
    } else {
      // 成功获取数据
      productList.value = prepareProductList;
      loadThumbnailController?.complete();
    }
  }
}

enum OrderPageStatus {
  thumbnailPage("ThumbnailPage"),
  detailPage("DetailPage"),
  specOptionPage("SpecOptionPage");

  final String status;

  const OrderPageStatus(this.status);

  static OrderPageStatus? fromString(String? status) {
    return OrderPageStatus.values.firstWhereOrNull((e) => e.status == status);
  }
}

enum OrderTabType {
  tabSearch(0),
  tabCategory(1),
  tabThumbnail(2);

  final int id;

  const OrderTabType(this.id);
}
